package com.coder.rental.security;

import com.alibaba.fastjson.JSON;
import com.coder.rental.utils.Result;
import com.coder.rental.utils.ResultCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author: zhanglin
 * @description:   登录认证失败处理方法
 * @date 2025/3/22
 */
@Component
public class LoginFailHandler implements AuthenticationFailureHandler {
    
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        //设置客户端响应的数据类型是json
        response.setContentType("application/json;charset=utf-8");
        //获取IO输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //定义一个错误状态码
        int code = ResultCode.ERROR;
        //响应信息
        String msg = null;
        //缓存过期
        if(exception instanceof AccountExpiredException){//用户账户过期异常
            code=ResultCode.UNAUTHENTICATED;
            msg="账户过期";
        }else if(exception instanceof BadCredentialsException) {//账户名和密码错误异常
            code=ResultCode.UNAUTHENTICATED;
            msg = "账户或密码错误";
        }else if(exception instanceof CredentialsExpiredException){//密码过期异常
            code=ResultCode.UNAUTHENTICATED;
            msg="密码过期";
        }else if(exception instanceof DisabledException){//账户被禁用异常
            code=ResultCode.UNAUTHORIZED;
            msg="账户被禁用";
        }else if (exception instanceof LockedException){//账户被锁定异常
            code=ResultCode.UNAUTHORIZED;
            msg="账号被锁定";
        }else if(exception instanceof InternalAuthenticationServiceException){//认证服务内部异常
            code=ResultCode.UNAUTHENTICATED;
            msg="账号不存在";
        }else if(exception instanceof CustomerAuthenticationException){//自定义异常
            code=ResultCode.UNAUTHORIZED;
            msg=exception.getMessage();
        }else{
            msg="登录失败";
        }
        //使用JSON格式化错误信息，并写入响应体
        String result = JSON.toJSONString(Result.fail().setCode(code).setMessage(msg));
        //设置输出流编码
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        //将数据发送出去，避免长期暂用缓冲区
        outputStream.flush();
        //关闭IO流
        outputStream.close();
    }
}
